Popular Searches
Popular Course Categories
Popular Courses

Working with Abstract Methods

Working with Abstract Methods

Abstraction, Interfaces, and Object Relationships

Working with Abstract Methods in Java

Course: Core Java Training

Topic: Working with Abstract Methods

Course Link: Core Java Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy


1. Introduction to Abstract Methods

Abstract methods are an important feature of object-oriented programming in Java. An abstract method defines a behavior that a class or interface requires without providing the method's implementation in that declaration. The implementation is supplied by a concrete subclass or implementing class.

Abstract methods are commonly used when several related classes must perform the same general operation but need different implementations. They help establish a consistent structure across classes while allowing each class to define its own behavior.

For example, different shapes can calculate their areas, but the formula for a circle is different from the formula for a rectangle. An abstract method named calculateArea() can define this common requirement, while each shape class provides its own calculation.

Learning Objectives

  • Understand the meaning and purpose of abstract methods.
  • Learn the syntax and rules for declaring abstract methods.
  • Understand the relationship between abstract methods and abstract classes.
  • Implement abstract methods in subclasses.
  • Work with abstract methods through inheritance and polymorphism.
  • Understand abstract methods in Java interfaces.
  • Identify common errors and apply best practices.

2. What Is an Abstract Method?

An abstract method is a method declared without a method body. It specifies the method's name, return type, parameters, and possibly a throws clause, but it does not contain the implementation.

In Java, the abstract keyword is used to declare an abstract method in an abstract class. An abstract method declaration ends with a semicolon instead of a method body.

Basic Syntax

abstract returnType methodName(parameters);

Example

abstract class Animal {
    abstract void makeSound();
}

In this example, makeSound() is an abstract method. It defines an operation that a concrete subclass must implement.

Understanding the Syntax

Component Meaning
abstract Declares the method without an implementation body.
void Specifies that the method does not return a value.
makeSound The name of the method.
() Indicates that the method has no parameters.
; Ends the declaration because there is no method body.

3. Why Do We Use Abstract Methods?

Abstract methods are useful when a common operation must be available in multiple classes but its implementation depends on the specific class.

  • Define a common contract: Require subclasses to implement particular operations.
  • Support different implementations: Allow each subclass to perform the operation in its own way.
  • Improve code organization: Keep common requirements in a shared parent class.
  • Support polymorphism: Call the same method through a parent reference while different objects provide different behavior.
  • Reduce duplicated design logic: Define a shared requirement once rather than relying on unrelated method names in each class.
  • Improve maintainability: Make required behavior explicit in the class hierarchy.

4. Relationship Between Abstract Methods and Abstract Classes

A class containing an abstract method must be declared abstract. An abstract class cannot be instantiated directly, but it can be extended by other classes.

An abstract class can contain both abstract methods and concrete methods. This allows it to define required behavior while also providing shared implementations.

Example

abstract class Vehicle {
    abstract void start();

    void stop() {
        System.out.println("Vehicle has stopped.");
    }
}

In this example:

  • Vehicle is an abstract class.
  • start() is an abstract method.
  • stop() is a concrete method because it has a body.
  • A concrete subclass must implement the inherited abstract method start().

5. Implementing Abstract Methods in Subclasses

When a concrete class extends an abstract class, it must implement all inherited abstract methods that remain unimplemented. If it does not implement them all, the subclass must also be declared abstract.

Example 1: Implementing an Abstract Method

abstract class Animal {
    abstract void makeSound();
}

class Dog extends Animal {
    @Override
    void makeSound() {
        System.out.println("Dog barks.");
    }
}

class Cat extends Animal {
    @Override
    void makeSound() {
        System.out.println("Cat meows.");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
        Cat cat = new Cat();

        dog.makeSound();
        cat.makeSound();
    }
}

Output

Dog barks.
Cat meows.

Explanation

  1. The Animal class declares the abstract method makeSound().
  2. The Dog class extends Animal and provides an implementation of makeSound().
  3. The Cat class also extends Animal but provides a different implementation.
  4. The main method creates objects of both concrete subclasses.
  5. Calling makeSound() produces behavior specific to each object.

6. Using the @Override Annotation

The @Override annotation indicates that a method is intended to override or implement an inherited method. It is recommended because the compiler can report an error if the method does not correctly match an overridable inherited method.

Example

abstract class Employee {
    abstract void performWork();
}

class Developer extends Employee {
    @Override
    void performWork() {
        System.out.println("Developer writes code.");
    }
}

The @Override annotation makes the developer's intention clear and helps detect errors such as misspelled method names or incompatible parameter lists.

7. Abstract Methods with Parameters

Abstract methods can accept parameters just like ordinary methods. A subclass implementation must use a compatible method signature and follow Java's overriding rules.

Example 2: Abstract Method with Parameters

abstract class Calculator {
    abstract int add(int a, int b);
}

class SimpleCalculator extends Calculator {
    @Override
    int add(int a, int b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        SimpleCalculator calculator = new SimpleCalculator();

        int result = calculator.add(15, 25);
        System.out.println("Sum: " + result);
    }
}

Output

Sum: 40

The abstract method specifies that an implementation must accept two integer values and return an integer. The SimpleCalculator class supplies the actual addition logic.

8. Abstract Methods with Return Values

An abstract method can return any valid Java type, including primitive types, objects, arrays, and other reference types. The concrete implementation must provide a compatible return type and satisfy the method's contract.

Example 3: Abstract Method Returning a Value

abstract class Shape {
    abstract double calculateArea();
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double calculateArea() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Circle circle = new Circle(5);

        System.out.printf("Area: %.2f%n", circle.calculateArea());
    }
}

Output

Area: 78.54

The abstract method defines the required operation. The Circle class implements the formula for calculating the area of a circle.

9. Abstract Methods with Multiple Subclasses

A single abstract method can be implemented differently by multiple subclasses. This approach is useful when several types share a general capability but perform the operation differently.

Example 4: Calculating Different Shape Areas

abstract class Shape {
    abstract double calculateArea();
}

class Circle extends Shape {
    double radius;

    Circle(double radius) {
        this.radius = radius;
    }

    @Override
    double calculateArea() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    double length;
    double width;

    Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    double calculateArea() {
        return length * width;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle(3);
        Shape rectangle = new Rectangle(4, 5);

        System.out.printf("Circle area: %.2f%n", circle.calculateArea());
        System.out.printf("Rectangle area: %.2f%n", rectangle.calculateArea());
    }
}

Output

Circle area: 28.27
Rectangle area: 20.00

Both objects are accessed through the Shape reference type. The implementation executed depends on the actual object, demonstrating runtime polymorphism.

10. Abstract Methods and Constructors

Abstract classes can have constructors, even though they cannot be instantiated directly. A subclass constructor invokes the abstract superclass constructor as part of object initialization.

Constructors themselves cannot be declared abstract because constructors are used to initialize objects rather than being inherited and overridden like instance methods.

Example

abstract class Person {
    String name;

    Person(String name) {
        this.name = name;
    }

    abstract void displayRole();
}

class Student extends Person {
    Student(String name) {
        super(name);
    }

    @Override
    void displayRole() {
        System.out.println(name + " is a student.");
    }
}

public class Main {
    public static void main(String[] args) {
        Student student = new Student("Amit");
        student.displayRole();
    }
}

Output

Amit is a student.

The Person constructor initializes the common name field, while Student implements the required abstract method.

11. Can an Abstract Class Have No Abstract Methods?

Yes. Java permits a class to be declared abstract even if it does not contain any abstract methods. Such a class may be intended to prevent direct instantiation or provide a shared base for subclasses.

Example

abstract class UtilityBase {
    void displayMessage() {
        System.out.println("Common utility behavior.");
    }
}

class Utility extends UtilityBase {
}

public class Main {
    public static void main(String[] args) {
        Utility utility = new Utility();
        utility.displayMessage();
    }
}

Output

Common utility behavior.

Although UtilityBase contains no abstract methods, it cannot be instantiated directly because it is declared abstract.

12. Can an Abstract Method Be Private, Static, or Final?

No. An abstract method cannot be declared private, static, or final.

Modifier Why It Cannot Be Used with an Abstract Method
private A private method is not inherited as an overridable method by subclasses.
static Static methods belong to the class rather than being dynamically overridden as instance methods.
final A final method cannot be overridden, which conflicts with the requirement for a subclass implementation.

Invalid Example

abstract class Example {
    // Invalid declarations:
    // private abstract void methodOne();
    // static abstract void methodTwo();
    // final abstract void methodThree();
}

Use an ordinary abstract instance method when a subclass is required to supply an implementation.

13. Abstract Methods in Interfaces

Interfaces are another important mechanism for defining abstract behavior in Java. A method declared in an interface without a body and without the default or static modifier is implicitly abstract. Such methods are also implicitly public.

Example 5: Abstract Method in an Interface

interface Printable {
    void print();
}

class Document implements Printable {
    @Override
    public void print() {
        System.out.println("Printing document.");
    }
}

class Photo implements Printable {
    @Override
    public void print() {
        System.out.println("Printing photo.");
    }
}

public class Main {
    public static void main(String[] args) {
        Printable document = new Document();
        Printable photo = new Photo();

        document.print();
        photo.print();
    }
}

Output

Printing document.
Printing photo.

The Document and Photo classes implement the same interface method differently. Notice that the implementation is declared public, as required when implementing a public interface method.

14. Abstract Methods and Runtime Polymorphism

Abstract methods often work together with runtime polymorphism. A superclass or interface reference can refer to different concrete objects, and the implementation associated with the actual object is executed when the method is called.

Example 6: Runtime Polymorphism

abstract class Notification {
    abstract void send();
}

class EmailNotification extends Notification {
    @Override
    void send() {
        System.out.println("Sending email notification.");
    }
}

class SMSNotification extends Notification {
    @Override
    void send() {
        System.out.println("Sending SMS notification.");
    }
}

public class Main {
    public static void main(String[] args) {
        Notification notification;

        notification = new EmailNotification();
        notification.send();

        notification = new SMSNotification();
        notification.send();
    }
}

Output

Sending email notification.
Sending SMS notification.

The abstract method establishes a shared contract. Runtime polymorphism allows each concrete notification type to provide its own implementation.

15. Abstract Methods vs Concrete Methods

Feature Abstract Method Concrete Method
Implementation body Does not have a method body. Has a method body.
Declaration Uses the abstract keyword in an abstract class. Does not use the abstract modifier.
Ending Ends with a semicolon. Uses braces containing the implementation.
Implementation requirement Must be implemented by a concrete subclass unless already implemented in the hierarchy. Can be inherited and used as provided, or overridden when permitted.
Purpose Defines required behavior without specifying its implementation. Provides executable behavior.
Example abstract void draw(); void draw() { System.out.println("Drawing"); }

16. Advantages of Abstract Methods

  • Consistency: They require concrete subclasses to implement important operations.
  • Flexibility: Each subclass can provide its own implementation.
  • Code organization: Common behavior requirements can be declared in one place.
  • Polymorphism: Different implementations can be called through a shared abstract type.
  • Maintainability: The class hierarchy makes required behavior explicit.
  • Extensibility: New subclasses can implement the same contract without changing all existing calling code.

17. Limitations and Challenges

  • Implementation obligation: Concrete subclasses must implement all inherited abstract methods.
  • Design complexity: Poorly planned abstract hierarchies can make code harder to understand.
  • Limited direct use: Abstract classes cannot be instantiated directly.
  • Inheritance constraints: A Java class can extend only one direct superclass.
  • Maintenance impact: Adding a new abstract method to a widely used abstract superclass may require changes to existing concrete subclasses.

18. Common Mistakes to Avoid

  • Declaring an abstract method inside a class that is not declared abstract.
  • Providing a method body for a method declared abstract.
  • Forgetting the semicolon at the end of an abstract method declaration.
  • Attempting to instantiate an abstract class directly.
  • Failing to implement all inherited abstract methods in a concrete subclass.
  • Using incompatible parameter lists when trying to override an abstract method.
  • Reducing the access level of an overridden method.
  • Declaring an abstract method as private, static, or final.
  • Forgetting to use public access when implementing an implicitly public interface method.

19. Best Practices for Working with Abstract Methods

  • Use abstract methods when subclasses must provide behavior that cannot be meaningfully implemented in the parent class.
  • Choose descriptive names that communicate the expected operation.
  • Keep abstract class responsibilities focused and cohesive.
  • Use @Override on subclass implementations to catch signature mistakes.
  • Document important requirements, expected results, and constraints for abstract methods.
  • Use an interface when you need to define a capability that can be implemented by unrelated classes.
  • Provide concrete shared methods in the abstract superclass when the behavior is genuinely common.
  • Test each concrete implementation as well as code that uses the common abstract type.

20. Real-World Applications of Abstract Methods

Application Abstract Method Possible Implementations
Graphics Application draw() Circle, Rectangle, Triangle
Payment System processPayment() Card payment, UPI payment, wallet payment
Notification System send() Email, SMS, push notification
Employee Management performWork() Developer, Manager, Tester
Report Generation generateReport() PDF report, CSV report, HTML report
File Processing processFile() CSV processor, JSON processor, XML processor

21. Practice Exercise 1: Abstract Class

Task: Create an abstract class named Appliance with an abstract method named turnOn().

Requirements

  1. Declare Appliance as an abstract class.
  2. Declare turnOn() as an abstract method.
  3. Create WashingMachine and Microwave subclasses.
  4. Implement turnOn() differently in each subclass.
  5. Create objects of both subclasses in the main method.
  6. Call turnOn() on each object.

Expected Output

Washing machine is turned on.
Microwave is turned on.

22. Practice Exercise 2: Abstract Method with Parameters

Task: Create an abstract class named BankAccount containing an abstract method named calculateInterest() that accepts a balance and an annual interest rate.

Requirements

  1. Declare an abstract method that accepts two double values.
  2. Create a SavingsAccount subclass.
  3. Implement the method to calculate simple annual interest using balance multiplied by the rate divided by 100.
  4. Call the method with a balance of 10000 and a rate of 5.
  5. Display the calculated interest.

Expected Output

Annual interest: 500.0

23. Mini Project: Shape Drawing Application

Create a simple Java program that uses abstract methods to represent different shapes.

Project Requirements

  • Create an abstract class named Shape.
  • Declare an abstract method named draw().
  • Declare another abstract method named calculateArea().
  • Create Circle and Rectangle subclasses.
  • Implement both methods in each subclass.
  • Create objects through Shape references.
  • Display each shape's drawing message and calculated area.

Learning Outcome: This project combines abstract classes, abstract methods, inheritance, method overriding, and runtime polymorphism.

24. Interview Questions and Answers

Q1. What is an abstract method in Java?

Answer: An abstract method is a method declared without an implementation body. It defines behavior that a concrete subclass or implementing class must provide.

Q2. Which keyword is used to declare an abstract method?

Answer: The abstract keyword is used to declare an abstract method in an abstract class.

Q3. Can a normal concrete class contain an abstract method?

Answer: No. A class containing an abstract method must be declared abstract.

Q4. Can an abstract class contain concrete methods?

Answer: Yes. An abstract class can contain both abstract and concrete methods.

Q5. Can we create an object of an abstract class?

Answer: No. An abstract class cannot be instantiated directly, but its reference type can refer to an object of a concrete subclass.

Q6. What happens if a subclass does not implement an abstract method?

Answer: The subclass must also be declared abstract unless the method has already been implemented by another class in its inheritance hierarchy.

Q7. Can abstract methods have parameters?

Answer: Yes. Abstract methods can accept parameters just like other methods.

Q8. Can abstract methods return values?

Answer: Yes. An abstract method can return a primitive value or a reference type.

Q9. Can an abstract method be private?

Answer: No. A private method is not inherited as an overridable method by subclasses.

Q10. Can an abstract method be static?

Answer: No. Static methods are associated with a class and are not overridden through runtime instance-method dispatch.

Q11. Can an abstract method be final?

Answer: No. A final method cannot be overridden, which conflicts with the role of an abstract method.

Q12. Can interfaces contain abstract methods?

Answer: Yes. Interface methods declared without a body and without default or static modifiers are implicitly abstract and public.

Q13. What is the purpose of @Override?

Answer: It indicates that a method is intended to override an inherited method and helps the compiler detect mistakes.

Q14. How do abstract methods support polymorphism?

Answer: Different subclasses can implement the same abstract method differently, and the appropriate implementation is selected at runtime for overridden instance methods.

25. Quick Revision Checklist

  • An abstract method has no implementation body.
  • The declaration ends with a semicolon.
  • A class containing an abstract method must be declared abstract.
  • An abstract class can contain abstract and concrete methods.
  • A concrete subclass must implement inherited abstract methods that remain unimplemented.
  • Abstract classes can have constructors and instance fields.
  • Abstract methods can accept parameters and return values.
  • Abstract methods cannot be private, static, or final.
  • Interface methods without bodies are implicitly abstract unless declared as another supported method kind.
  • The @Override annotation helps detect implementation mistakes.
  • Abstract methods support abstraction and work naturally with runtime polymorphism.
  • Use abstract methods to define required behavior across related classes.

26. Conclusion

Abstract methods are an essential part of Java abstraction. They define required operations without prescribing a specific implementation, allowing concrete subclasses to provide behavior suitable for their needs.

By working with abstract methods, abstract classes, interfaces, and method overriding, developers can build applications that are flexible, reusable, and easier to maintain. Practicing the examples and exercises in these notes will strengthen your understanding of Core Java and object-oriented programming.


Learn Core Java with JustAcademy

Continue improving your Java programming and object-oriented development skills with these learning resources.

Previous Next
whatsapp